<?php

namespace App\Http\Controllers\Admin\Shop;

use App\Http\Controllers\AdminController;
use App\Jobs\SetAdminLog;
use App\Models\Shop\Order;
use App\Models\Shop\Store;
use Carbon\Carbon;
use Illuminate\Http\Request;

use App\Http\Requests;
use Maatwebsite\Excel\Facades\Excel;

class OrderController extends AdminController
{
    public function getIndex(Request $request)
    {

        //获取商品分类
        $order = $this->findOrder($request);
        //获取店铺
        $store = Store::all()->keyBy('id');
        //分类
        return view('admin.shop.order')->with(['order' => $order['order'], 'store' => $store, 'sum' => $order['sum']]);
    }

    private function findOrder(Request $request)
    {
        $order = new Order();
        if($request->has('storeID'))
        {
            $order = $order->where('storeID', $request->input('storeID'));
        }
        if($request->has('payState'))
        {
            $order = $order->where('payState', $request->input('payState'));
        }
        if($request->has('logisticsState'))
        {
            $order = $order->where('logisticsState', $request->input('logisticsState'));
        }
        //时间筛选
        if($request->has('time'))
        {
            $time = explode(' - ',$request->input('time'));
            if(isset($time[0]) && isset($time[1]))
            {
                $startime = $time[0];
                $endtime = $time[1];
                $order = $order->where('created_at','>=',$startime)->where('created_at','<=',$endtime);
            }
        }
        //搜索

        if($request->has('searchType') && $request->has('keyword'))
        {
            switch ($request->input('searchType'))
            {
                case 'orderNumber':
                case 'uid':
                    $order = $order->where($request->input('searchType'), $request->input('keyword'));
                    break;
                case 'address':
                    $order = $order->where($request->input('searchType'), 'LIKE', '%'.$request->input('keyword').'%');
                    break;
            }
        }
        $sum = $order->sum('amount');
        $order = $order->orderBy('id', 'desc')->paginate(20);
        return [
            'order'     =>  $order,
            'sum'       =>  $sum
        ];
    }

    public function getEdit()
    {}

    public function getExcel(Request $request)
    {
        $order = $this->findOrder($request);
        $data = [];
        //获取店铺
        $store = Store::all()->keyBy('id');
        $s = [];
        foreach ($order['order'] as $k=>$v)
        {
            switch ($v->logisticsState)
            {
                case 0:
                    $logisticsState = '未配送';
                    break;
                case 1:
                    $logisticsState = '配送中';
                    break;
                case 2:
                    $logisticsState = '已送达';
                    break;
                default:
                    $logisticsState = '未配送';
            }
            $v->orderList = json_decode($v->orderList) ? json_decode($v->orderList) : $v->orderList;
            if(is_string($v->orderList))
            {
                $orderList = $v->orderList;
            }else{
                $orderList = [];
                foreach ($v->orderList as $vv)
                {
                    if($vv->thumb != '')
                    {
                        array_push($orderList, $vv->title.' x '.$vv->num);
                    }else{
                        if(isset($vv->discount))
                        {
                            array_push($orderList, $vv->title.' '.$vv->discount.' 折');
                        }else{
                            array_push($orderList, $vv->title.' '.$vv->price.' 円');
                        }
                    }
                }
                $orderList = implode(',', $orderList);
            }
            $data[$k] = [
                '订单号'       =>  $v->orderNumber,
                '店铺'         =>  $store[$v->storeID]->name,
                '总价'         =>  $v->amount,
                '所购商品'     =>  $orderList,
                '配送信息'     =>  $v->address,
                '付款状态'     =>  ($v->payState == 0) ? '未付款' : '已付款',
                '配送状态'     =>  $logisticsState,
                '订单时间'     =>  $v->created_at,
                '备注'         =>  $v->remark
            ];
            if($k%2 != 0)
            {
                $s[$k+2] = '#cccccc';
            }
        }
        $data[] = [
            '订单号'       =>  '',
            '店铺'         =>  '',
            '总价'         =>  '',
            '所购商品'     =>  '',
            '配送信息'     =>  '',
            '付款状态'     =>  '',
            '配送状态'     =>  '合计',
            '订单时间'     =>  $order['sum'],
            '备注'         =>  ''
        ];
        //导出Excel
        Excel::create('订单信息',function($excel) use($data, $s) {
            $excel->sheet('用户提现日志', function($sheet) use($data, $s) {
                $sheet->freezeFirstRow();
                $sheet->cells('A1:I1', function($cells) {
                    $cells->setFontWeight('bold');
                });
                foreach ($s as $j=>$vv)
                {
                    $sheet->cells('A'.$j.':I'.$j, function($cells) use ($vv) {
                        $cells->setBackground($vv);
                    });
                }
                $sheet->setWidth(array(
                    'A'     =>  24,
                    'B'     =>  23,
                    'C'     =>  10,
                    'D'     =>  40,
                    'E'     =>  40,
                    'F'     =>  10,
                    'G'     =>  10,
                    'H'     =>  18,
                    'I'     =>  10
                ));
                $sheet->fromArray($data);
            });
        })->export('xlsx');
    }

    public function getExcelPrint(Request $request)
    {
        $order = $this->findOrder($request);
        $data = [];
        //获取店铺
        $store = Store::all()->keyBy('id');
        $s = [];
        foreach ($order['order'] as $k=>$v)
        {
            $v->orderList = json_decode($v->orderList) ? json_decode($v->orderList) : $v->orderList;
            if(is_string($v->orderList))
            {
                $orderList = $v->orderList;
            }else{
                $orderList = [];
                foreach ($v->orderList as $vv)
                {
                    if($vv->thumb != '')
                    {
                        array_push($orderList, $vv->title.' x '.$vv->num);
                    }else{
                        if(isset($vv->discount))
                        {
                            array_push($orderList, $vv->title.' '.$vv->discount.' 折');
                        }else{
                            array_push($orderList, $vv->title.' '.$vv->price.' 円');
                        }
                    }
                }
                $orderList = implode(',', $orderList);
            }
            $data[$k] = [
                '订单号'       =>  $v->orderNumber,
                '店铺'         =>  $store[$v->storeID]->name,
                '总价'         =>  $v->amount,
                '所购商品'     =>  $orderList,
                '配送信息'     =>  $v->address,
                '订单时间'     =>  $v->created_at,
                '备注'         =>  $v->remark
            ];
            if($k%2 != 0)
            {
                $s[$k+2] = '#cccccc';
            }
        }
        $data[] = [
            '订单号'       =>  '',
            '店铺'         =>  '',
            '总价'         =>  '',
            '所购商品'     =>  '',
            '配送信息'     =>  '合计',
            '订单时间'     =>  $order['sum'],
            '备注'         =>  ''
        ];
        //导出Excel
        Excel::create('打印订单',function($excel) use($data, $s) {
            $excel->sheet('用户提现日志', function($sheet) use($data, $s) {
                $sheet->freezeFirstRow();
                $sheet->cells('A1:I1', function($cells) {
                    $cells->setFontWeight('bold');
                });
                foreach ($s as $j=>$vv)
                {
                    $sheet->cells('A'.$j.':I'.$j, function($cells) use ($vv) {
                        $cells->setBackground($vv);
                    });
                }
                $sheet->setWidth(array(
                    'A'     =>  24,
                    'B'     =>  23,
                    'C'     =>  10,
                    'D'     =>  40,
                    'E'     =>  40,
                    'F'     =>  18,
                    'G'     =>  10
                ));
                $sheet->fromArray($data);
            });
        })->export('xlsx');
    }

    /**
     * 更改配送状态
     * @param Request $request
     * @return string
     */
    public function postLogisticsState(Request $request)
    {
        $order = Order::find($request->input('id'));
        if(!empty($order))
        {
            $origin = $order->toArray();
            $order->logisticsState = $request->input('state');
            if ($order->save())
            {
                //setLog
                $this->setLog('shop_order', json_encode($origin), json_encode($request->except('_token')));
                return json_encode([
                    'code'      =>  1,
                    'message'   =>  getLang('Tips', 'updateSuccess')
                ]);
            }
        }
        return json_encode([
            'code'      =>  0,
            'message'   =>  getLang('Tips', 'updateFail')
        ]);
    }
    /**
     * 记录日志
     * @param string$type 类型 create update delete
     * @param json null $origin 事件发生前
     * @param json null $ending 事件发生后
     */
    private function setLog($type, $origin = NULL, $ending = NULL)
    {
        switch ($type)
        {
            case 'shop_order':
                $event = [
                    'msg'   =>  'shop_order.show',
                    'type'  =>  'Update'
                ];
                break;
        }
        //push to queue
        $geoIP = geoip()->getLocation();
        $this->dispatch(new SetAdminLog($this->user->id, $geoIP, $event['msg'], Carbon::now(), $event['type'], $origin, $ending));
    }
}
